package mybatisplus.spring.boot.admin.common.util;

import mybatisplus.spring.boot.admin.common.enums.WordEnum;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.util.*;

public class UrlUtil {

    public static String parseUrlPair(Object o, WordEnum wordEnum) throws IllegalAccessException {
        return parseObjectUrlPair(o,wordEnum,"=","&");
    }

    public static String parseObjectUrlPair(Object o, WordEnum wordEnum,String kvJoinSymbol,String paramJoinSymbol) throws IllegalAccessException {
        List<Field> fieldList=new ArrayList<>();
        for (Class<?> clazz = o.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                Field[] fields = clazz.getDeclaredFields();
                if(fields!=null && fields.length>0) fieldList.addAll(Arrays.asList(fields));
            } catch (Exception e) {
                // 这里甚么都不要做！并且这里的异常必须这样写，不能抛出去。
                // 如果这里的异常打印或者往外抛，则就不会执行clazz=clazz.getSuperclass(),最后就不会进入到父类中了
            }
        }
        Map<String, Object> map = new HashMap<>();
        List<String> keyList=new ArrayList<>();
        for (Field field : fieldList) {
            field.setAccessible(true);
            String name = field.getName();
            Object value = field.get(o);
            if (value != null){
                if(wordEnum==WordEnum.LOW) name=name.toLowerCase();
                else if(wordEnum==WordEnum.UP) name=name.toUpperCase();
                keyList.add(name);
                map.put(name, value);
            }
        }
        if(ListUtil.isNull(keyList)) return null;
        String[] keyArray=ListUtil.toArray(keyList, String.class);
        Arrays.sort(keyArray);
        StringBuilder urlBuilder = new StringBuilder();
        for(String key : keyArray){
            urlBuilder.append(key).append(kvJoinSymbol).append(map.get(key)).append(paramJoinSymbol);
        }
        return urlBuilder.deleteCharAt(urlBuilder.length() - 1).toString();
    }

    public static String parseMapUrlPair(Map<String, String> map, WordEnum wordEnum,String kvJoinSymbol,String paramJoinSymbol) throws Exception {
        if(map==null || map.size()<=0) return null;
        String[] keyArray=new String[map.keySet().size()];
        map.keySet().toArray(keyArray);
        Arrays.sort(keyArray);
        StringBuilder urlBuilder = new StringBuilder();
        for(String key : keyArray){
            urlBuilder.append(key).append(kvJoinSymbol).append(map.get(key)).append(paramJoinSymbol);
        }
        if(StringUtils.isNotBlank(paramJoinSymbol)){
            urlBuilder = urlBuilder.deleteCharAt(urlBuilder.length() - 1);
        }
        return urlBuilder.toString();
    }


}
